<template>
  <el-container class='elheight'>
    <el-aside class='appTree'>
      <app-tree :tree-data="treeData" v-on:appTreeClick="appTreeClick"></app-tree>
    </el-aside>
    <el-main>
      <el-container>
        <el-header class="dzy-main-header">
          <div class="btn-group-el">
            <btn-group :currentSelectedData="currentSelectedData" @btnClickCallback="btnClickCallback"></btn-group>
          </div>
          <div class="dzy-custom-search-box">
            <div>
              案件编号：<el-input placeholder="请输入内容" v-model="selectForm.caseNumber" clearable class="dzy-custom-input"></el-input>
            </div>
            <div>
              姓名：<el-input placeholder="请输入内容" v-model="selectForm.name" clearable class="dzy-custom-input"></el-input>
            </div>
            <div>
              身份证号：<el-input placeholder="请输入内容" v-model="selectForm.credentialsNumber" clearable class="dzy-custom-input"></el-input>
            </div>
            <div>
              <el-button @click="searchHandleClick" type="primary" icon="el-icon-search">查询</el-button>
            </div>
          </div>
        </el-header>
        <el-main>
          <app-table
            :page-data="pageData"
            :table-columns="tableColumns"
            v-on:currentChange="handleCurrentChange"
            v-on:handleCheckedRows="handleCheckedRows">
          </app-table>
          <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" class="custom-dialog_style_twoLine" :before-close="cancel" :close-on-click-modal="false">
            <el-form :model="formData"
                     :rules="rules"
                     ref="formData"
                     :disabled="showOnly"
                     label-width="50%">
              <el-form-item label="案件编号：" prop="caseNumber" label-width="30%">
                <el-input v-model="formData.caseNumber" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="姓名：" prop="name" label-width="30%">
                <el-input v-model="formData.name" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="曾用名：" label-width="30%">
                <el-input v-model="formData.usedName" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="证件代码：" prop="credentialsCode" label-width="30%">
                <el-select v-model="formData.credentialsCode" clearable placeholder="请选择">
                  <el-option v-for="(item,index) in codeOptions" :key="index" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="证件号码：" prop="credentialsNumber" label-width="30%">
                <el-input v-model="formData.credentialsNumber" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="性别：" prop="gender" label-width="30%">
                <el-select v-model="formData.gender" clearable placeholder="请选择">
                  <el-option v-for="(item,index) in genderOption" :key="index" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="出生日期：" prop="birthday" label-width="30%">
                <div class="block">
                  <el-date-picker
                    v-model="formData.birthday"
                    type="date"
                    value-format="timestamp"
                    format="yyyy 年 MM 月 dd 日"
                    placeholder="选择日期"
                    :picker-options="dataPickerBeforeTodayOptions">
                  </el-date-picker>
                </div>
              </el-form-item>
              <el-form-item label="国籍（地区）：" label-width="30%">
                <el-select v-model="formData.nationality" autocomplete="off" clearable filterable placeholder="请选择">
                  <el-option v-for="(item,index) in nationalityOption" :key="index" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="民族：" label-width="30%">
                <el-select v-model="formData.nation" clearable filterable placeholder="请选择">
                  <el-option v-for="(item,index) in nationOption" :key="index" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="籍贯：" label-width="30%">
                <el-input v-model="formData.birthplace" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="婚姻状况：" label-width="30%">
                <div class="block">
                  <el-cascader
                    v-model="formData.maritalStatusArr"
                    placeholder="请选择"
                    :options="maritalStatusOption"
                    filterable
                    :props="dictProps"
                    clearable
                    change-on-select>
                  </el-cascader>
                </div>
              </el-form-item>
              <el-form-item label="政治面貌：" label-width="30%">
                <el-select v-model="formData.politicalStatus" clearable filterable placeholder="请选择">
                  <el-option v-for="(item,index) in politicalStatusOption" :key="index" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="学历：" label-width="30%">
                <div class="block">
                  <el-cascader
                    v-model="formData.educationArr"
                    placeholder="请选择"
                    :options="educationOption"
                    filterable
                    :props="dictProps"
                    clearable
                    change-on-select>
                  </el-cascader>
                </div>
              </el-form-item>
              <el-form-item label="宗教信仰：" label-width="30%">
                <el-select v-model="formData.religion" clearable filterable placeholder="请选择">
                  <el-option v-for="(item,index) in religionOption" :key="index" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="职业类别：" label-width="30%">
                <el-select v-model="formData.careerCategory" clearable filterable placeholder="请选择">
                  <el-option v-for="(item,index) in careerCategoryOption" :key="index" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="职业：" label-width="30%">
                <el-input v-model="formData.career" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="服务处所：" label-width="30%">
                <el-input v-model="formData.servicePlace" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="户籍地：" label-width="30%">
                <el-input v-model="formData.householdAddr" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="户籍门(楼)详址：" label-width="30%">
                <el-input v-model="formData.householdAddrDetail" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="现住地：" label-width="30%">
                <el-input v-model="formData.currentAddr" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="现住门(楼)详址：" label-width="30%">
                <el-input v-model="formData.currentAddrDetail" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="街道/社区/网格：" prop="gridIdArr" label-width="30%">
                <div class="block">
                  <el-cascader
                    placeholder="请选择"
                    :options="treeData"
                    filterable
                    clearable
                    :props="gridIdProps"
                    v-model="formData.gridIdArr">
                  </el-cascader>
                </div>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer" v-if="isfooterBtnShow">
              <el-button @click="cancel">取 消</el-button>
              <el-button type="primary" @click="save('formData')">确 定</el-button>
            </div>
          </el-dialog>
        </el-main>
      </el-container>
    </el-main>
  </el-container>
</template>

<script>
import AppTree from '@/components/common/AppTree'
import AppTable from '@/components/AppTable'
import BtnGroup from '@/components/BtnGroup'
import {getAllRegion} from '@/utils/region'
import {validateIdefer} from '@/utils/validate'
import {getUserGridTree} from '@/utils/SessionDataUtil'
import {getDictDataOption} from '@/utils/getDictDataOption'
import {getVictim, createVictim, updateVictim, delVictim, getHomicide, getVictimById} from '@/http/PublicSecurityAppApi'
export default {
  data () {
    var checkCaseId = async (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入案件编号'))
      } else {
        let param = { caseNo: value }
        let res = await getHomicide(param).then(resp => {
          return resp
        })
        if (res.code && res.code === '200') {
          let data = res.data
          if (data.total === 0) {
            return callback(new Error('案件不存在'))
          } else {
            setTimeout(() => {
              callback()
            }, 1000)
          }
        }
      }
    }
    return {
      dialogFormVisible: false,
      isfooterBtnShow: true,
      treeData: [],
      pageData: {},
      dialogTitle: '',
      currentSelectedData: [],
      showOnly: false,
      tableColumns: [
        { prop: 'caseNumber', label: '案件编号' },
        { prop: 'name', label: '受害人姓名' },
        { prop: 'credentialsNumber', label: '证件号码' },
        { prop: 'gender', label: '性别', formatter: this.genderFormatter, width: '50' }
      ],
      dataPickerBeforeTodayOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now()
        }
      },
      tableDada: [],
      formData: {},
      selectForm: {},
      gridIdProps: {
        label: 'name',
        value: 'id'
      },
      dictProps: {
        label: 'name',
        value: 'code'
      },
      rules: {
        caseNumber: [
          { required: true, validator: checkCaseId, trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        credentialsCode: [
          { required: true, message: '请选择证件代码', trigger: 'blur' }
        ],
        credentialsNumber: [
          { validator: validateIdefer, required: true, trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'blur' }
        ],
        birthday: [
          { required: true, message: '请选择出生年月', trigger: 'blur' }
        ],
        gridIdArr: [
          { required: true, message: '请选择所属网格', trigger: 'blur' }
        ]
      },
      codeOptions: [],
      nationalityOption: [],
      genderOption: [],
      nationOption: [],
      maritalStatusOption: [],
      politicalStatusOption: [],
      educationOption: [],
      religionOption: [],
      careerCategoryOption: []
    }
  },
  components: {
    AppTree,
    BtnGroup,
    AppTable
  },
  mounted () {
    this.getTreeData()
    this.getTableData()
  },
  methods: {
    // 格式化性别
    genderFormatter (row, column) {
      let genderOption = getDictDataOption('性别')
      let resGender = ''
      for (let i = 0; i < genderOption.length; i++) {
        if (genderOption[i].code === row.gender) {
          resGender = genderOption[i].name
          break
        }
      }
      return resGender
    },
    getTreeData () {
      let data = getUserGridTree()
      if (data && data instanceof Array) {
        this.treeData = data
      }
    },
    save (formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          this.$alert('请填写正确表单格式', '', {
            confirmButtonText: '确定'
          })
          return ''
        } else {
          if (this.formData.gridIdArr && this.formData.gridIdArr !== 0) {
            let index = this.formData.gridIdArr.length - 1
            let data = {}
            data.id = this.formData.gridIdArr[index]
            data.items = this.treeData
            data.isGetAllId = true
            this.formData.allGridId = getAllRegion(data)
          } else {
            this.formData.allGridId = ''
          }
          this.formData.maritalStatus = this.formData.maritalStatusArr ? this.formData.maritalStatusArr.join(',') : ''
          this.formData.education = this.formData.educationArr ? this.formData.educationArr.join(',') : ''
          if (this.formData.id) {
            updateVictim(this.formData).then(resp => {
              if (resp.code && resp.code === '200') {
                this.dialogFormVisible = false
                this.$message({
                  type: 'success',
                  message: '修改成功'
                })
                this.getTableData()
              } else {
                this.$message({
                  type: 'info',
                  message: resp.message
                })
                return ''
              }
            })
          } else {
            createVictim(this.formData).then(resp => {
              if (resp.code && resp.code === '200') {
                this.dialogFormVisible = false
                this.$message({
                  type: 'success',
                  message: '添加成功'
                })
                this.getTableData()
              } else {
                this.$message({
                  type: 'info',
                  message: resp.message
                })
                return ''
              }
            })
          }
        }
      })
    },
    del (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          rows.forEach(row => {
            delVictim(row).then(resp => {
              if (resp.code && resp.code === '200') {
                this.$message({
                  type: 'success',
                  message: '删除成功'
                })
                this.getTableData()
              } else {
                this.$message({
                  type: 'info',
                  message: resp.message
                })
                return ''
              }
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    cancel () {
      this.dialogFormVisible = false
      this.formData = {}
    },
    getTableData (param) {
      getVictim(param).then(resp => {
        if (resp.code && resp.code === '200') {
          this.pageData = resp.data
          if (this.pageData.items && this.pageData.items instanceof Array) {
            this.tableData = this.pageData.items
          }
        } else {
          this.$message({
            type: 'info',
            message: resp.message
          })
          return ''
        }
      })
    },
    handleCurrentChange (val) {
      this.selectForm.offset = (val - 1) * 10
      this.getTableData(this.selectForm)
    },
    btnClickCallback (callbackData) {
      if (callbackData.btnType === 'delete') {
        this.dialogFormVisible = false
        let rows = callbackData.rows
        this.del(rows)
      } else {
        this.isfooterBtnShow = callbackData.btnType !== 'get'
        this.codeOptions = getDictDataOption('证件代码')
        this.nationalityOption = getDictDataOption('国家和地区')
        this.genderOption = getDictDataOption('性别')
        this.nationOption = getDictDataOption('民族')
        this.maritalStatusOption = getDictDataOption('婚姻状况')
        this.politicalStatusOption = getDictDataOption('政治面貌')
        this.educationOption = getDictDataOption('学历')
        this.religionOption = getDictDataOption('宗教信仰')
        this.careerCategoryOption = getDictDataOption('职业分类')
        if (callbackData.btnType === 'post') {
          this.dialogTitle = '新增'
          if (this.formData.gridIdArr) {
            let arr = this.formData.gridIdArr
            this.formData = {}
            this.$set(this.formData, 'gridIdArr', arr)
          } else {
            this.formData = {}
          }
        } else {
          let obj = {}
          obj = JSON.stringify(callbackData.rows[0])
          this.formData = JSON.parse(obj)
          let maritalStatusArr = this.formData.maritalStatus !== '' && this.formData.maritalStatus !== null ? this.formData.maritalStatus.split(',') : []
          let educationArr = this.formData.education !== '' && this.formData.education !== null ? this.formData.education.split(',') : []
          this.$set(this.formData, 'maritalStatusArr', maritalStatusArr)
          this.$set(this.formData, 'educationArr', educationArr)
          let regionData = {}
          regionData.id = this.formData.gridId
          regionData.items = this.treeData
          let gridIdArr = getAllRegion(regionData)
          this.$set(this.formData, 'gridIdArr', gridIdArr)
        }
        this.showOnly = callbackData.sohwOnly
        this.dialogTitle = callbackData.dialogTitle
        this.dialogFormVisible = true
      }
    },
    handleCheckedRows (rows) {
      if (rows.length <= this.currentSelectedData.length && rows.length === 1) this.currentSelectedData = []
      if (rows && rows instanceof Array && rows.length > 0) {
        let m = this
        getVictimById(rows[0].id).then(resp => {
          if (resp.code && resp.code === '200') {
            m.currentSelectedData = [resp.data]
            m.formData = resp.data
          } else {
            m.$message({
              type: 'info',
              message: resp.message
            })
            return ''
          }
        })
      } else {
        this.currentSelectedData = []
        this.formData = {}
      }
    },
    appTreeClick (data) {
      let gridData = {}
      gridData.id = data.id
      gridData.items = this.treeData
      let gridIdArr = getAllRegion(gridData)
      this.$set(this.formData, 'gridIdArr', gridIdArr)
      this.selectForm.likeAllGridId = data.id
      this.selectForm.offset = 0
      this.getTableData(this.selectForm)
    },
    searchHandleClick () {
      this.selectForm.offset = 0
      this.getTableData(this.selectForm)
    }
  }
}
</script>
